package com.android.activity;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.android.controler.RemoteControlSender;

public class SenderActivity extends Activity {
	private static final boolean DEBUG = true;
	private static final int REQUEST_ENABLE_BT = 1;
	private static final int REQUEST_CONNECT_BT = 2;
	private static final String TAG = "RCS.sender";
	public static final int ID_MSG = 1;
	public static final String MSG = "mensaje";
	private BluetoothAdapter mBluetoothAdapter = null;
	private RemoteControlSender mRCS = null;
	private boolean noStop = true;
	HiloPlay hiloPlay=null;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.sender);
		if (DEBUG)
			Log.e(TAG, "onCreate");

		mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
		if (mBluetoothAdapter == null) {
			if (DEBUG)
				Log.e(TAG,
						getResources().getString(
								R.string.ERROR_NOT_SUPPORT_BLUETOOTH));
			Toast.makeText(
					this,
					getResources().getString(
							R.string.ERROR_NOT_SUPPORT_BLUETOOTH),
					Toast.LENGTH_LONG).show();
			finish();
			return;
		}

		this.onPreviousButtomClick();
		this.onNextButtomClick();
		this.onFirstButtomClick();
		this.onLastButtomClick();
		this.onPlayButtomClick();
		this.onStopButtomClick();
	}

	@Override
	public void onStart() {
		super.onStart();
		if (DEBUG)
			Log.e(TAG, "onStart");

		if (!mBluetoothAdapter.isEnabled()) {
			Intent enableIntent = new Intent(
					BluetoothAdapter.ACTION_REQUEST_ENABLE);
			startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
		} else {
			if (mRCS == null)
				runRCS();
		}
	}

	private final Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case ID_MSG:
				if (msg.arg1 == R.integer.RCS_IDLE) {
					//
				} else if (msg.arg1 == R.integer.RCS_CONNECTING) {
					if (DEBUG)
						Log.e(TAG,
								getResources().getString(R.string.ID_MSG)
										+ getResources().getString(
												R.string.RCS_CONNECTING));
					Toast.makeText(
							getApplicationContext(),
							msg.getData().getString(MSG)
									+ getResources().getString(
											R.string.RCS_CONNECTING),
							Toast.LENGTH_SHORT).show();
				} else if (msg.arg1 == R.integer.RCS_CONNECTED) {
					if (DEBUG)
						Log.e(TAG,
								getResources().getString(R.string.ID_MSG)
										+ getResources().getString(
												R.string.RCS_CONNECTED));
					Toast.makeText(
							getApplicationContext(),
							msg.getData().getString(MSG)
									+ getResources().getString(
											R.string.RCS_CONNECTED),
							Toast.LENGTH_SHORT).show();
				} else if (msg.arg1 == R.integer.RCS_OUTPUT_STREAM) {
					if (DEBUG)
						Log.e(TAG,
								getResources().getString(R.string.ID_MSG)
										+ getResources().getString(
												R.string.RCS_OUTPUT_STREAM));
					Toast.makeText(
							getApplicationContext(),
//							msg.getData().getString(MSG)+
									 getResources().getString(
											R.string.RCS_OUTPUT_STREAM),
							Toast.LENGTH_SHORT).show();
				}
				break;
			}
		}
	};

	private void runRCS() {
		Log.d(TAG, "runRCS");
		mRCS = new RemoteControlSender(this, mHandler);
	}

	// Recoger resultados.
	public void onActivityResult(int requestCode, int resultCode, Intent i) {
		if (DEBUG)
			Log.d(TAG, "onActivityResult ");
		switch (requestCode) {
		// Dialogo de activacion de Bluetooth.
		// se regista en sender.onStart()
		case REQUEST_ENABLE_BT:
			if (resultCode == Activity.RESULT_OK) {
				if (DEBUG)
					Log.e(TAG, "ENABLE_BT OK");
				runRCS();
			} else {
				if (DEBUG)
					Log.e(TAG, "ENABLE_BT OK");
				finish();
			}
			break;
		// Resultado de intento de conexion BT.
		// se registra en sender.
		case REQUEST_CONNECT_BT:
			if (resultCode == Activity.RESULT_OK) {
				// Recoger la MAC y pedir la conexion a RCS.
				if (DEBUG)
					Log.e(TAG, "CONNECT_BT OK");
				String direccion = i.getExtras().getString(
						ListActivity.DIRECCION);
				BluetoothDevice bt = mBluetoothAdapter
						.getRemoteDevice(direccion);
				mRCS.conecta(bt);
				if (DEBUG)
					Log.e(TAG, "enviando id :" + R.integer.COMANDO_SIGUIENTE);
				if (DEBUG)
					Log.e(TAG,
							"enviando valor :"
									+ getResources().getInteger(
											R.integer.COMANDO_SIGUIENTE));
				if (DEBUG)
					Log.e(TAG,
							"convertido a :"
									+ Integer
											.toString(
													getResources()
															.getInteger(
																	R.integer.COMANDO_SIGUIENTE))
											.getBytes());
				if (DEBUG)
					Log.e(TAG,
							"vuelta es :"
									+ +(new Integer(
											new String(
													Integer.toString(
															getResources()
																	.getInteger(
																			R.integer.COMANDO_SIGUIENTE))
															.getBytes()))
											.intValue()));
				// mRCS.write(Integer.toString(getResources().getInteger(R.integer.COMANDO_SIGUIENTE)).getBytes());
				// mRCS.write("hola".getBytes());
			} else {
				if (resultCode == Activity.RESULT_CANCELED) {
					if (DEBUG)
						Log.e(TAG, "CONNECT_BT RESULT_CANCELED");
				} else {
					if (DEBUG)
						Log.e(TAG, "CONNECT_BT ??");
					finish();
				}
			}
			break;
		}
	}

	// Boton de Menu de Android
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.menu_principal, menu);
		return true;
	}

	// Seleccion de dispositivo remoto y lanzar la conexion.
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.scan:
			if (DEBUG)
				Log.e(TAG, "scan");
			Intent serverIntent = new Intent(this, ListActivity.class);
			startActivityForResult(serverIntent, REQUEST_CONNECT_BT);
			return true;
		}
		return false;
	}

	/**
	 * Acci�n para el bot�n next
	 */
	public void onNextButtomClick() {
		Button next = (Button) findViewById(R.id.btn_next);

		next.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				if (mRCS != null)
					mRCS.write(Integer.toString(
							getResources().getInteger(
									R.integer.COMANDO_SIGUIENTE)).getBytes());

			}
		});
	}

	/**
	 * Acci�n para el boton previus
	 */
	public void onPreviousButtomClick() {
		Button previous = (Button) findViewById(R.id.btn_previous);
		// previous.setVisibility(0);
		previous.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				if (mRCS != null)
					mRCS.write(Integer.toString(
							getResources().getInteger(
									R.integer.COMANDO_ANTERIOR)).getBytes());
			}
		});
	}
	
	/**
	 * Acci�n para el boton first
	 */
	public void onFirstButtomClick() {
		Button first = (Button) findViewById(R.id.btn_first);
		// previous.setVisibility(0);
		first.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				if (mRCS != null)
					mRCS.write(Integer.toString(
							getResources().getInteger(
									R.integer.COMANDO_PRIMERO)).getBytes());
			}
		});
	}
	
	/**
	 * Acci�n para el boton last
	 */
	public void onLastButtomClick() {
		Button last = (Button) findViewById(R.id.btn_last);
		// previous.setVisibility(0);
		last.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				if (mRCS != null)
					mRCS.write(Integer.toString(
							getResources().getInteger(
									R.integer.COMANDO_ULTIMO)).getBytes());
			}
		});
	}
	
	/**
	 * Acci�n para el boton play
	 */
	public void onPlayButtomClick() {
		Button play = (Button) findViewById(R.id.btn_play);
		// previous.setVisibility(0);
		play.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				if (mRCS != null){
					if (null == hiloPlay) {
						hiloPlay = new HiloPlay();
						hiloPlay.start();
					}
				}
//					mRCS.write(Integer.toString(
//							getResources().getInteger(
//									R.integer.COMANDO_PLAY)).getBytes());
			}
		});
	}
	
	/**
	 * Acci�n para el boton stop
	 */
	public void onStopButtomClick() {
		Button stop = (Button) findViewById(R.id.btn_stop);
		// previous.setVisibility(0);
		stop.setOnClickListener(new View.OnClickListener() {
			public synchronized void onClick(View v) {
				if (mRCS != null){
					noStop=false;
					if(null!=hiloPlay){
						hiloPlay.cancel();
						hiloPlay = null;
					}
				}
//					mRCS.write(Integer.toString(
//							getResources().getInteger(
//									R.integer.COMANDO_STOP)).getBytes());
			}
		});
	}
	private class HiloPlay extends Thread {
		
		

		public void cancel() {
			
		}
		public synchronized void run(){
			noStop=true;
			while(noStop){
				if (mRCS != null)
					mRCS.write(Integer.toString(
							getResources().getInteger(
									R.integer.COMANDO_SIGUIENTE)).getBytes());
				try {
					Log.e(TAG, "Durmiendo " );
					sleep(2000);
				} catch (InterruptedException ie) {
					Log.e(TAG, ie.toString());
				}
			}
		}
	}
}